//
//  TeacherCourseListVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/6/26.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "TeacherCourseListVC.h"
#import "TeacherCourseListCell.h"
#import "TeacherCourseListModel.h"
#import "CourseEvaluateVC.h"
#import "CourseEvaluationSegmentVC.h"
#import "CurriculumSignedVC.h"
#import "CurriculumAllEvaVC.h"
#import "HNStudentSignVC.h"
#import "HNThreeGoodEvaDetailVC.h"
#import "HNThreeGoodEvaVC.h"
@interface TeacherCourseListVC ()
{
    IBOutlet UITableView *_TableView;
}

/**
 数据存放
 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/**
 当前页码
 */
@property (nonatomic, assign) NSInteger CurrentPage;
/**
 临时页码
 */
@property (nonatomic, assign) NSInteger TempPage;

@end

@implementation TeacherCourseListVC


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"课程列表";
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"ddddd" style:(UIBarButtonItemStyleDone) target:self action:@selector(rightAction)];
//

    // 配置TableView
    [self SetupTableView];

}



//- (void)rightAction{
//
//
//    [self.navigationController pushViewController:[ZYAttendanceRecordController new] animated:YES];
//
//
//}




#pragma mark  - 配置
/**
 配置TableView
 */
- (void)SetupTableView
{
    // 占位
    _TableView.tableFooterView = [UIView new];
    _TableView.tableHeaderView = [UIView new];
    // 预注册
    [_TableView registerNib:[UINib nibWithNibName:[TeacherCourseListCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    // 预估高度
    _TableView.rowHeight = 90;
    //默认页码
    self.CurrentPage = 1;
    // 下拉刷新
    _TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        //取当前页码给临时页码
        self.TempPage = self.CurrentPage;
        //设当前页码为1
        self.CurrentPage = 1;
        //请求
        [self RefreshData];
    }];
    //上拉加载
    _TableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        //请求
        [self RefreshData];
    }];
    //开始刷新
    [_TableView.mj_header beginRefreshing];
}


/**
 刷新失败时，判断是否需要从临时页码里取出来给当前页码
 */
- (void)GetPage
{
    if (self.CurrentPage == 1)
    {
        self.CurrentPage = self.TempPage;
    }
}

/**
 结束刷新

 @param Index 0:结束刷新 1:提示没有更多数据 2:tableView数据源更新
 */
- (void)EndRefresh:(NSInteger)Index;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (Index)
        {
            case 0:
            {
                [_TableView.mj_header endRefreshing];
                [_TableView.mj_footer endRefreshing];
            }
                break;
            case 1:
            {
                [_TableView.mj_footer endRefreshingWithNoMoreData];
            }
                break;
            case 2:
            {
                [_TableView reloadData];
            }
                break;
            default:
                break;
        }
    });
}



#pragma mark - 网络请求
static void extracted(TeacherCourseListVC *object, NSDictionary *Params) {
    [NetManager Get:LLBaseURLTeacher(@"trainLesson.do") Auth:YES Params:Params Success:^(id Obj) {
        
        //结束刷新
        [object EndRefresh:0];
        //判断是否加载成功
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 取值
            NSArray *DataList = Obj[@"t"][@"dataList"];
            if (DataList.count == 0)
            {
                // 提示没有更多数据了
                [object EndRefresh:1];
            }
            else
            {
                
                //下拉刷新成功时，清除原数据
                if (object.CurrentPage == 1)
                {
                    [object.DataArr removeAllObjects];
                }
                
                [DataList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    //转模型
                    TeacherCourseListModel *Model = [TeacherCourseListModel HNObjectValuesForKey:(NSDictionary *)obj];
                    [object.DataArr addObject:Model];
                }];
                
                //数据请求成功，页码加1
                object.CurrentPage += 1;
                
                //刷新
                [object EndRefresh:2];
            }
        }
        else
        {
            //页码处理
            [object GetPage];
            //显示错误信息
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        
        //结束刷新
        [object EndRefresh:0];
        //页码处理
        [object GetPage];
        //显示错误信息
        [MBProgressHUD showError:NetErr];
    }];
}

/**
 网络请求
 */
- (void)RefreshData
{

    NSDictionary *Params = @{
                             @"action"      :@"getTrainLessonForRecord",
                             @"pageNumber"  :@(self.CurrentPage)
                             };
    extracted(self, Params);
}

/** 发起上架或下架的请求 */
- (void)RefreshDataForSellStatusWithID:(NSNumber *)ID sellStatus:(NSNumber *)sellStatus Success:(void (^)())Success {

    [HUD showHUD];
    NSDictionary *params = @{
                             @"action":@"changeSellStatus",
                             @"id":ID,
                             @"sellStatus":sellStatus
                             };
    [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:params Success:^(id Obj) {

        [Obj[@"code"] isEqualToNumber:@1000] ? Success():[HUD showError:Obj[@"msg"]];
    } Fail:^(NSError *Error) {

        [HUD showError:NetErr];
    }];

}

#pragma mark - TableView代理
//区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

//Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取值
    TeacherCourseListModel *Model = self.DataArr[indexPath.row];
    // 实例Cell
    TeacherCourseListCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    // 点语法
    Cell.Model = Model;

    Cell.ClickButton = ^(NSNumber *ID) {

        // 点击了评价事件
        [self MgrClickEva:ID Name:Model.name];

    };
    Cell.ClickEva = ^(NSNumber *ID) {

        // 点击了集体评价
        [self signButtonAction:ID Name:Model.name];
    };

    Cell.ClickUploadCourse = ^ (NSNumber *ID) {


    };

    Cell.ClickSellStatus = ^(TeacherCourseListModel *model, UIButton *Btn) {

        // 点击了上下架
        [self MgrSellStatusWithModel:model sender:Btn];
    };
    return Cell;
}




#pragma mark - 处理方法
/**
 集体评价
 */
- (void)MgrClickEva:(NSNumber *)ID Name:(NSString *)Name
{
    HNThreeGoodEvaVC *VC = [[HNThreeGoodEvaVC alloc] init];
    VC.ID = ID;
    VC.Name = Name;
    VC.HNThreeGoodEvaMode = HNThreeGoodEvaModeTeacher;
    [self.navigationController pushViewController:VC animated:YES];

}



/**
 点击了评价事件
 */
- (void)signButtonAction:(NSNumber *)ID Name:(NSString *)Name
{
//    CurriculumSignedVC *VC = [[CurriculumSignedVC alloc] init];
//    VC.ID = ID;
//    VC.IsTeacher = YES;
    HNStudentSignVC *VC = [[HNStudentSignVC alloc] init];
    VC.ID = ID;
    VC.IsTeacher = YES;
    [self.navigationController pushViewController:VC animated:YES];

}





/** 处理点击上架下架操作 */
- (void)MgrSellStatusWithModel:(TeacherCourseListModel *)Model sender:(UIButton *)sender {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:sender.selected?@"是否下架该课程":@"是否上架该课程" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [alert addAction:[UIAlertAction actionWithTitle:sender.selected?@"下架":@"上架" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 发起请求
        [self RefreshDataForSellStatusWithID:Model.ID sellStatus:sender.selected ? @0:@1 Success:^{
            // 请求成功的话再改变按钮的状态
            sender.selected = !sender.selected;
            Model.sellStatus = sender.selected ? @1:@0;
        }];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - Setter
- (NSMutableArray *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}


@end
